<template>
  <div class="app-container">
    <div
      v-show="
        !modifyInfo.visible && !detailsInfo.visible && !detailListInfo.visible
      "
    >
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :slip-select-request="slipSelectRequest"
          :clear-type="clearType"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-retract>
            <el-button :disabled="!canRetract" @click="retract()"
              >撤回</el-button
            >
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>

      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
        @sortChange="sortChange"
      >
        <template v-slot:col-orderNo="scope">
          <span class="slip-edit" @click="showDetail(scope.row)">{{
            scope.row.orderNo
          }}</span>
        </template>
        <template v-slot:col-sumQty="scope">
          <span
            >{{ $fn.qtyFormatter(scope.row.sumStorageQty) }}/{{
              $fn.qtyFormatter(scope.row.sumQty)
            }}</span
          >
        </template>
      </table-container>
    </div>
    <use-application-details
      v-if="detailsInfo.visible"
      :id="detailsInfo.id"
      v-model:visible="detailsInfo.visible"
      :title="detailsInfo.title"
      @returnBack="getList"
    />
    <!-- 新增或修改 -->
    <use-application-modify
      v-if="modifyInfo.visible"
      :orderId="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :fromType="modifyInfo.fromType"
      saveFrom=""
      :storeOrderId="modifyInfo.storeOrderId"
      :storeOrderNo="modifyInfo.storeOrderNo"
      :useReturnImportStore="modifyInfo.useReturnImportStore"
      @returnModify="returnModify"
    />
    <detailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></detailList>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
  </div>
</template>

<script setup name="useReturnApplication">
import TableContainer from '@/components/TableContainer/index'
import {
  getUseReturnApplicationCustomizeList,
  deleteUseReturnApplication,
  submitUseReturnApplication,
  retractUseReturnApplication,
} from '@/api/use'
import UseApplicationModify from './modify'
import UseApplicationDetails from './details'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/index')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)
const detailList = defineAsyncComponent(() => import('./detailList'))

// 过滤相关配置
const filterInfo = reactive({
  sortArr: [],
  copyQueryMap: {},
  query: {
    sortString: '',
    queryMap: {
      depotIdAuth: {
        asTbName: 'use_return_application_order',
        columnName: 'depot_id',
        queryType: 'IN',
        queryCategory: 'AND',
        value: 'depotAuth',
      },
    },
    customizeUserVO: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btnList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('useReturnApplication:add'),
    },
    {
      type: 'slot',
      label: '撤回',
      value: 'retract',
      show: proxy.$permission('useReturnApplication:retract'),
    },
  ],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: undefined,
  selections: [],
  data: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('useReturnApplication:update'),
        ifRender(row) {
          return row.status === 1
        },
      },
      {
        label: '提交',
        event: submit,
        show: proxy.$permission('useReturnApplication:submit'),
        ifRender(row) {
          return row.status === 1
        },
      },
      {
        label: '撤回',
        event: retract,
        show: proxy.$permission('useReturnApplication:retract'),
        ifRender(row) {
          return row.status === 2
        },
      },
      {
        label: '删除',
        event: _delete,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('useReturnApplication:del'),
        ifRender(row) {
          return row.status === 1
        },
      },
    ],
  },
})

// 表单相关
const formInfo = reactive({
  ref: null,
  data: {},
  fieldList: [
    { label: '领用部门', value: 'name', type: 'input' },
    { label: '领用人', value: 'code', type: 'input' },
    { label: '领用仓库', value: 'code', type: 'input' },
  ],
  rules: {},
  labelWidth: '100px',
})
//新增或更新相关
const modifyInfo = reactive({
  visible: false,
  title: '',
  id: '',
  fromType: '',
  storeOrderId: '',
  storeOrderNo: '',
  useReturnImportStore: '',
})
const detailsInfo = reactive({
  visible: false,
  id: '',
})
const detailListInfo = reactive({
  visible: false,
})
const preferenceInfo = reactive({
  visible: false,
})
const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})
const clearType = ref(true)
const slipSelectRequest = ref(true)
const time = ref([])
const dialogInfo = ref()

watch(
  () => filterInfo.query.applicationTimeGreater,
  (val) => {
    if (!val) {
      time.value = null
    }
  }
)
const canRetract = computed(() => {
  return (
    tableInfo.selections.length &&
    tableInfo.selections.filter((row) => row.status !== 2).length === 0
  )
})

const toPageVal = computed(() => {
  return proxy.$store.state.settings.toPage
})
let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPageVal.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'useReturnApplication' && el.url === val.url) {
                detailsInfo.visible = false
                modifyInfo.visible = false
                detailsInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  proxy.$nextTick(() => {
                    detailsInfo.visible = true
                    detailsInfo.orderNo = val.orderNo
                    detailsInfo.id = val.orderId
                    sessionStorage.setItem('storeRowId', val.orderId)
                  })
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})

let obj = {
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'use_return_application_status',
    show: false,
    hidden: true,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

async function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  let arr = [
    {
      asTbName: 'use_return_application_order',
      columnName: 'depot_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'depotAuth',
    },
  ]
  filterInfo.query.queryMap = {}
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data
  await getList()
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
}
function returnModify() {
  if (modifyInfo.id) {
    search()
  } else {
    getList()
  }
}
// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
// 创建
function create() {
  modifyInfo.id = null
  modifyInfo.visible = true
  modifyInfo.title = '新增领用退回单'
  modifyInfo.fromType = ''
  modifyInfo.storeOrderId = ''
  modifyInfo.storeOrderNo = ''
  modifyInfo.useReturnImportStore =
    proxy.$store.state.permission.systemConfig.use_application_return_import_store_order.toString()
}
// 编辑
function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.id = row.id
  modifyInfo.visible = true
  modifyInfo.title = '修改领用退回单'
  modifyInfo.fromType = ''
  modifyInfo.storeOrderId = ''
  modifyInfo.storeOrderNo = ''
  modifyInfo.useReturnImportStore =
    proxy.$store.state.permission.systemConfig.use_application_return_import_store_order.toString()
  if (row.sourceType === 20) {
    modifyInfo.fromType = 'useStore'
    modifyInfo.storeOrderId = row.sourceId
    modifyInfo.storeOrderNo = row.sourceOrderNo
    modifyInfo.useReturnImportStore = ''
  }
  console.log(modifyInfo)
}
// 查看明细
function showDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailsInfo.id = row.id
  detailsInfo.visible = true
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
// 删除
function _delete(row) {
  if (row.status != 1) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '当前数据状态无法删除',
    })
  } else {
    deleteUseReturnApplication([row.id]).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  }
}
function close() {
  dialogInfo.value.visible = false
  formInfo.data = {}
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
//提交
function submit(row = undefined) {
  const ids = getIds(row)
  submitUseReturnApplication(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
//撤回
function retract(row = undefined) {
  const ids = getIds(row)
  retractUseReturnApplication(ids).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
function getIds(row = undefined) {
  let ids = []
  if (row) {
    ids.push(row.id)
  } else {
    ids = tableInfo.selections.map((row) => row.id)
  }
  return ids
}

function clearSearch() {
  clearType.value = !clearType.value
  advancedSearchInfo.data = {}
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'useReturnApplicationOrderIndex-com.slip.spd.entity.vo.use.UseReturnApplicationOrderVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getUseReturnApplicationCustomizeList
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.sortArr)
    filterInfo.sortArr = arr
    filterInfo.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
</script>

<style scoped></style>
